#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
#include <QMessageBox>
#include "form.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    //连接信号和槽
    connect(ui->Btn_login, &QPushButton::clicked, this, &Dialog::on_Btn_login_clicked);
    connect(ui->Btn_cancel, &QPushButton::clicked,this, &Dialog::on_Btn_cancel_clicked);

    //设置密码输入框为隐藏模式
    ui->LEd_password->setEchoMode(QLineEdit::Password);
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::on_Btn_login_clicked()
{
    //获取用户输入
    QString username = ui->LEd_username->text();
    QString password = ui->LEd_password->text();
    //验证用户输入
    if (username.isEmpty() || password.isEmpty())
    {
        QMessageBox::warning(this,"Login Failed","Username and password cannot be empty.");
        return;
    }
    if (User::validateUser(username, password))
    {
        qDebug() << "Login successful!";
        currentUser.setUsername(username);
        currentUser.setPassword(password);

        accept();
    }
    else {
        if (!User::userExists(username))
        {
            qDebug() << "Creating new user account for" << username;
            User newUser(username,password);
            newUser.save();

            qDebug() << "New user created and logged in successfully!";
            currentUser.setUsername(username);
            currentUser.setPassword(password);

            accept();
        }
        else
        {
            qDebug() << "Invalid username or password.";
            QMessageBox::warning(this,"Login Failed","Invalid username or password.");
        }

    }

}

void Dialog::on_Btn_cancel_clicked()
{
    reject();
}
